package org.istt.web;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.istt.domain.AttachFile;
import org.istt.domain.Category;
import org.istt.domain.CategoryType;
import org.istt.domain.DocumentType;
import org.istt.domain.Field;
import org.istt.service.AttachFileManager;
import org.istt.service.CategoryManager;
import org.istt.service.CategoryTypeManager;
import org.istt.service.DocumentTypeManager;
import org.istt.service.FieldManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AttachFileAction extends ActionSupport {
    /**
	 * 
	 */
	private static final long serialVersionUID = 9012754123343759656L;
	private String[] arrAttachFiles;
    private AttachFile attachFile;
    @Autowired
    private AttachFileManager attachFileManager;
    private List<AttachFile> attachFiles;
    private String cancel;
    private CategoryManager categoryMgr;
    private CategoryTypeManager categoryTypeManager;
    //NDTHO.13/10/2011
    private String cateId;

	private String cateTypeId;
	private String delete;
	private DocumentTypeManager documentTypeMgr;
	private String fieldId;
	private FieldManager fieldManager;
    private String id;
    private final Log log = LogFactory.getLog(AttachFileAction.class);
    private List lstCategory;
    private AttachFileManager mgr;
    private String numberOfCopy;
	private String save;
	private String search;
	private String selectedCategory;
	
	public void setSaveSortMessage() {
		ActionContext.getContext().getSession()
				.put("message", getText("attachFile.msg.add"));
	}
	
	public String edit() {
		lstCategory = categoryMgr.getList();
        // check for an add
		log.debug("--------ID: "+id);
        if (id != null) {
        	attachFile = mgr.getAttachFile(id);
        	log.debug("--------ATT NAME: "+attachFile.getAttachFileName());
			cateId = attachFile.getCategory().getId() + "";
			cateTypeId = attachFile.getCategoryType().getId() + "";
			
			Category c = categoryMgr.get(NumberUtils.toLong(cateId));
			Field field = c.getField(); 
			fieldId = field == null ? null : field.getId() + "";
			
        } else {
        	attachFile = new AttachFile();
        	if(StringUtils.isNotEmpty(cateId) && cateId != "0"){
        		attachFile.setCategory(categoryMgr.get(Long.parseLong(cateId)));
        	}
        	if(StringUtils.isNotEmpty(cateTypeId) && cateTypeId != "0"){
        		attachFile.setCategoryType(categoryTypeManager.get(Long.parseLong(cateTypeId)));
        	}
        }        
        return SUCCESS;
    }

	public String copy() {
		lstCategory = categoryMgr.getList();
		// check for an add
		log.debug("--------ID: "+id);
		if (id != null) {
			AttachFile sourceObj =  mgr.getAttachFile(id);
			attachFile = new AttachFile();
			attachFile.setAttachFileName(sourceObj.getAttachFileName());
			attachFile.setCategory(sourceObj.getCategory());
			attachFile.setCategoryType(sourceObj.getCategoryType());
			attachFile.setDocumentType(sourceObj.getDocumentType());
			attachFile.setHeading(sourceObj.getHeading());
			attachFile.setNumberOfCopy(sourceObj.getNumberOfCopy());
			attachFile.setPosition(sourceObj.getPosition());
			attachFile.setId(null);
			
			log.debug("--------ATT NAME: "+attachFile.getAttachFileName());
			cateId = attachFile.getCategory().getId() + "";
			cateTypeId = attachFile.getCategoryType().getId() + "";
			
			Category c = categoryMgr.get(NumberUtils.toLong(cateId));
			Field field = c.getField(); 
			fieldId = field == null ? null : field.getId() + "";
			
		} else {
		}        
		return SUCCESS;
	}
	
	public String execute() {
        if (cancel != null) {
            return "cancel";
        }
        if (delete != null) {
            return "delete";
        }
        if (search != null) {
        	return search();
        }
        
        return SUCCESS;
    }

	public String executeListForm(){
    	if(save!=null){
    		return saveSort();
    	}else{
    		return listAttachByCate();
    	}
    }

	public String[] getArrAttachFiles() {
		return arrAttachFiles;
	}

	public AttachFile getAttachFile() {
		return attachFile;
	}
	
	public AttachFileManager getAttachFileManager() {
		return attachFileManager;
	}
	public List getAttachFiles() {
		if(cateId!=null && !"".equals(cateId) && StringUtils.isNotEmpty(cateTypeId)){
    		attachFiles = mgr.findAttachFileByCate(NumberUtils.toLong(cateId), NumberUtils.toLong(cateTypeId));
        }
		return attachFiles;
	}
	
	public String getCancel() {
		return cancel;
	}
	
	public CategoryTypeManager getCategoryTypeManager() {
		return categoryTypeManager;
	}
	public String getCateId() {
		return cateId;
	}
	
	public String getCateTypeId() {
		return cateTypeId;
	}

	/**
	 * @return the catList
	 */
	public List<NameValuePair> getCatList() {
		List<NameValuePair> catList = new ArrayList<NameValuePair>();
		if (!StringUtils.isEmpty(fieldId)) {
			if (log.isDebugEnabled()) {
				log.debug("fieldId is equal to " + fieldId
						+ " getting categories");
			}

		List<Category> categories = categoryMgr.getByFieldId(NumberUtils.toLong(fieldId));
			for (Category c : categories) {
				NameValuePair elm = new NameValuePair();
				elm.setName(c.getCategoryName());
				/*if(StringUtils.length(c.getCategoryName()) > 80)
					elm.setName(StringUtils.substring(c.getCategoryName(), 0, 80)+"...");
				else elm.setName(StringUtils.substring(c.getCategoryName(), 0, 80));*/
				
				elm.setValue(c.getId() + "");
				catList.add(elm);
			}
		}
		return catList;
	}

	public String getDelete() {
		return delete;
	}
	
	public DocumentTypeManager getDocumentTypeMgr() {
		return documentTypeMgr;
	}

	/**
	 * @return the fieldId
	 */
	public String getFieldId() {
		return fieldId;
	}

	/**
	 * @return the fields
	 */
	public List<Field> getFields() {
		return fieldManager.getList();
	}

	public String getId() {
		return id;
	}

	public List getLstCategory() {
		return lstCategory;
	}

	public List<CategoryType> getLstCategoryType() {
		return categoryTypeManager.getList();
		
	}
    public List<DocumentType> getLstDocumentType() {
		return documentTypeMgr.getList();
		
	}
    public AttachFileManager getMgr() {
		return mgr;
	}

    public String getNumberOfCopy() {
		return numberOfCopy;
	}
    
    public String getSave() {
		return save;
	}
    
    public String getSearch() {
		return search;
	}

	public String getSelectedCategory() {
		return selectedCategory;
	}

	// Check attach file is in use
	public boolean isAllowDelete() {
		log.debug("Entering method isAllowDelete...");
		boolean isValid = true;
		if (StringUtils.isNotEmpty(getId()) && attachFileManager.countFileUseAttach(NumberUtils.toLong(getId()))!=0){
			isValid = false;
		}
		return isValid;
	}
    
    
    public boolean isValid() {
    	boolean result = false;
    	
    	try {
    		result = mgr.isUnique(new String[]{"attachFileName"}, new String[]{attachFile.getAttachFileName().toString()}, 
    				attachFile.getId(), 
    				NumberUtils.toLong(cateId) ,
    				NumberUtils.toLong(cateTypeId) ,
    				attachFile.getDocumentType().getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
    
    public String list() { 
    	attachFiles = mgr.getAttachFiles();
        return SUCCESS; 
    }

    public String listAttachByCate() { 
    	if (log.isDebugEnabled()){
    		log.debug("Entering 'listAttachByCate' method | cateId: "+cateId);
    	}
    	
    	if(StringUtils.isEmpty(fieldId)){
    		List<Field> lstFields = this.fieldManager.getList();
    		if(lstFields.size()!=0){
    			fieldId = lstFields.get(0).getId() + "";
    			if(StringUtils.isEmpty(cateId)){
    	    		List<Category> lstCategories = this.categoryMgr.getByFieldId(NumberUtils.toLong(fieldId));
    	    		if(lstCategories.size()!=0) cateId = lstCategories.get(0).getId() + "";
    	    	}
    		}
    	}
    	
    	if(StringUtils.isEmpty(cateTypeId)){
    		List<CategoryType> lstCategoryTypes = this.categoryTypeManager.getList();
    		if(lstCategoryTypes.size()!=0) cateTypeId = lstCategoryTypes.get(0).getId() + "";
    	}
    	
    	attachFiles = mgr.findAttachFileByCate(NumberUtils.toLong(cateId), NumberUtils.toLong(cateTypeId));
    	
        return SUCCESS; 
    }
    
    public String loadSearch() {
		//lstCategory = categoryMgr.getList();
		return SUCCESS;
	}
    
    
    public String remove() {
		
//		mgr.removeAttachFile(attachFile.getId().toString());
		mgr.removeAttachFile(getId());
        
        List args = new ArrayList();
        //args.add(attachFile.getAttachFileName());
        ActionContext.getContext().getSession().put("message", getText("attachFile.msg.delete", args));
		
        return SUCCESS;
    }
    
    public String save() {
        if (log.isDebugEnabled()) {
            log.debug("entering 'save' method");
        }
        
        //Update Category
        Category category = categoryMgr.get(NumberUtils.toLong(cateId));
        attachFile.setCategory(category);

        //Update Type of Category
        CategoryType categoryType = categoryTypeManager.get(NumberUtils.toLong(cateTypeId));
        attachFile.setCategoryType(categoryType);
        
        //In case of adding new 
        if(attachFile.getPosition()!=null){
        	
        }else{
        	int position = this.attachFileManager.countAttachFile(NumberUtils.toLong(cateId) ,
        			attachFile.getCategoryType().getId(), 
        			attachFile.getDocumentType().getId());
        	
        	attachFile.setPosition(position);
        }
        
        mgr.saveAttachFile(attachFile);
        
        List args = new ArrayList();
        args.add(attachFile.getAttachFileName());
        
        ActionContext.getContext().getSession().put("message", 
                getText("attachFile.msg.add", args));
        
        //If cateId is not null, redirect to category form
//        if(cateId!=null && !"".equals(cateId)){
//        	log.debug("BACK TO CATEGORY DETAIL...");
//        	return "back";
//        }
        return SUCCESS;
    }
    
    public String search() {
		if (log.isDebugEnabled()) {
			log.debug("entering 'search attachFile' method");
		}		

		if (NumberUtils.toLong(cateId) !=0l) {
			Category cat = categoryMgr.get(NumberUtils.toLong(cateId));
			attachFiles = this.mgr.searchAttachFile(cat, attachFile.getAttachFileName(), attachFile.getCategoryType());
			lstCategory = categoryMgr.getList();
		}
		return SUCCESS;
	}
    
    public void setArrAttachFiles(String[] arrAttachFiles) {
		this.arrAttachFiles = arrAttachFiles;
	}
    
    public void setAttachFile(AttachFile attachFile) {
		this.attachFile = attachFile;
	}

	public void setAttachFileManager(AttachFileManager attachFileManager) {
        this.mgr = attachFileManager;
    }

	public void setAttachFiles(List attachFiles) {
		this.attachFiles = attachFiles;
	}

	public void setCancel(String cancel) {
        this.cancel = cancel;
    }


	public void setCategoryMgr(CategoryManager categoryMgr) {
		this.categoryMgr = categoryMgr;
	}

	public void setCategoryTypeManager(CategoryTypeManager categoryTypeManager) {
		this.categoryTypeManager = categoryTypeManager;
	}

	public void setCateId(String cateId) {
		this.cateId = cateId;
	}

	public void setCateTypeId(String cateTypeId) {
		this.cateTypeId = cateTypeId;
	}

	public void setDelete(String delete) {
        this.delete = delete;
    }

	@Autowired
	public void setDocumentTypeMgr(DocumentTypeManager documentTypeMgr) {
		this.documentTypeMgr = documentTypeMgr;
	}
	

	/**
	 * @param fieldId
	 *            the fieldId to set
	 */
	public void setFieldId(String fieldId) {
		this.fieldId = fieldId;
	}
	/**
	 * @param fieldManager
	 *            the fieldManager to set
	 */
	public void setFieldManager(FieldManager fieldManager) {
		this.fieldManager = fieldManager;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setLstCategory(List lstCategory) {
		this.lstCategory = lstCategory;
	}

	public void setMgr(AttachFileManager mgr) {
		this.mgr = mgr;
	}

	public void setNumberOfCopy(String numberOfCopy) {
		this.numberOfCopy = numberOfCopy;
	}
	
	public void setSave(String save) {
		this.save = save;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public void setSelectedCategory(String selectedCategory) {
		this.selectedCategory = selectedCategory;
	}

	public String saveSort(){
    	if (log.isDebugEnabled()){
    		log.debug("Entering 'sort' method ....");
    	}
    	if(arrAttachFiles.length!=0) {
    		for (int i = 0; i < arrAttachFiles.length; i++) {
				log.debug("Item: ["+i+"] = "+arrAttachFiles[i]);
				String attFileId = arrAttachFiles[i];
				AttachFile attFile = attachFileManager.getAttachFile(attFileId);
				attFile.setPosition(i);
				
				this.attachFileManager.saveAttachFile(attFile);
				
				setSaveSortMessage();
			}
    	}
    	
    	return SUCCESS;
    }

//	public void validate() {
//		if (log.isDebugEnabled()) {
//			log.debug("entering validate");
//		}
//	}
	
}
